<?php
require_once ('database.php');

class Account {
	
	protected static $table_name = 'mat_account';
	protected static $db_fields = array('friends', 'student_id','username','password','name_lastname');
	
	private $student_id;
	private $username;
	private $password;
	private $name_lastname;
	
//	public $friends = array("KMUTNB" => "Pinij", "SRIAYUDHYA" => "John");
	
	public function __construct()
	{
		
	}
	
	public function get_username()
	{
		return $this->username;
	}
	
	public function get_user_fullname()
	{
		return $this->name_lastname;
	}
	
	public function set_username($username)
	{
		$this->username = $username;
	}
	
	public function set_fullname($firstname, $lastname) 
	{
		$this->name_lastname = $firstname." ".$lastname;
	}
	
	public function set_password($password)
	{
		$this->password = $password;
	}

	
	public static function find_by_id($id) {
		$result_array = self::find_by_sql("SELECT * FROM " . self::$table_name .
            " WHERE student_id ='".$id."' LIMIT 1");
        return !empty($result_array) ? array_shift($result_array) : false;
	}
	
	public static function find_all(){
		return self::find_by_sql("SELECT * FROM " . self::$table_name);
		
	}
	
public static function find_by_sql($sql = "")
	{
		global $database;
		$result_set = $database->query($sql);
		$object_array = array();
		while ($row = $database->fetch_array($result_set))
		{
			$object_array[] = self::instantiate($row);
		}
		return $object_array;
	}

	/**
	 * GeneralDatabase::instantiate()
	 * 
	 * @param mixed $record
	 * @return
	 */
	private  static function instantiate($record)
	{
		// Could check that $record exists and is an array
		$object = new self;

		foreach ($record as $attribute => $value)
		{
			if ($object->has_attribute($attribute))
			{
				$object->$attribute = $value;
			}
		}
		return $object;
	}

	private function has_attribute($attribute)
	{
		// We don't care about the value, we just want to know if the key exists
		// Will return true or false
		return array_key_exists($attribute, $this->attributes());
	}
	
	public function get_account_info()
	{
		return $this->sanitized_attributes();
	}

	protected function sanitized_attributes()
	{
		global $database;
		$clean_attributes = array();
		// sanitize the values before submitting
		// Note: does not alter the actual value of each attribute
		foreach ($this->attributes() as $key => $value)
		{
			$clean_attributes[$key] = $database->escape_value($value);
		}
		return $clean_attributes;
	}


	protected  function attributes()
	{
		// return an array of attribute names and their values
		$attributes = array();
		foreach (self::$db_fields as $field)
		{
			if (property_exists($this, $field))
			{
				$attributes[$field] = $this->$field;
			}
		}
		return $attributes;
	}
    
    public function save()
    {
        // A new record won't have an id yet.
        //return isset($this->subject_id) ? $this->update() : $this->create();
        if($this->student_id == "")
        {
            return $this->create();
        }
        else
        {
            return $this->update();
        }
    }
    
    public function create()
    {
        global $database;
        // Don't forget your SQL syntax and good habits:
        // - INSERT INTO table (key, key) VALUES ('value', 'value')
        // - single-quotes around all values
        // - escape all values to prevent SQL injection
        //        $query = "select * from ".self::$table_name." where";
        //        $query .= " username = '".$attributes["username"]."'";
        //        $result = $database->query($query);
        //        if($database->affected_rows() > 0)
        //        {
        //            return false;
        //        }
        //        else
        //        {
        //
        //        }
        $attributes = $this->sanitized_attributes();
        $sql = "INSERT INTO " . self::$tableName . " (";
        $sql .= join(", ", array_keys($attributes));
        $sql .= ") VALUES ('";
        $sql .= join("', '", array_values($attributes));
        $sql .= "')";
        if ($database->query($sql))
        {
            //$this->student_id = $database->insert_id();
            return true;
        } else
        {
            return false;
        }
    }

    public function update()
    {
        global $database;
        // Don't forget your SQL syntax and good habits:
        // - UPDATE table SET key='value', key='value' WHERE condition
        // - single-quotes around all values
        // - escape all values to prevent SQL injection
        $attributes = $this->sanitized_attributes();
        $attribute_pairs = array();
        foreach ($attributes as $key => $value)
        {
            $attribute_pairs[] = "{$key}='{$value}'";
        }
        $sql = "UPDATE " . self::$table_name . " SET ";
        $sql .= join(", ", $attribute_pairs);
        $sql .= " WHERE student_id=" . $database->escape_value($this->student_id);
        $database->query($sql);
        return ($database->affected_rows() == 1) ? true : false;
    }

    public function delete()
    {
        global $database;
        // Don't forget your SQL syntax and good habits:
        // - DELETE FROM table WHERE condition LIMIT 1
        // - escape all values to prevent SQL injection
        // - use LIMIT 1
        $sql = "DELETE FROM " . self::$table_name;
        $sql .= " WHERE student_id=" . $database->escape_value($this->student_id);
        $sql .= " LIMIT 1";
        $database->query($sql);
        return ($database->affected_rows() == 1) ? true : false;

        // NB: After deleting, the instance of User still
        // exists, even though the database entry does not.
        // This can be useful, as in:
        //   echo $user->first_name . " was deleted";
        // but, for example, we can't call $user->update()
        // after calling $user->delete().
    }
	
	
}

?>